﻿using Colorful.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Colorful.CMS.Core
{
    public static class CMSDbHelper
    {
        #region 获取数据库接口
        public static DbContext GetDb(string database = "")
        {
            if (string.IsNullOrEmpty(database))
                database = DbSetting.Database;
            return new DbContext(DbSetting.ConnectionString, database);
        }
        public static void SetCache(string key, string value, TimeSpan? absoluteExpiration = null)
        {
            using (var db = GetDb())
            {
                db.SetCache(key, value, absoluteExpiration);
            }
        }
        public static void SetCache<T>(string key, T value, TimeSpan? absoluteExpiration = null)
        {
            SetCache(key, JsonHelper.ToJson(value), absoluteExpiration);
        }
        public static string GetCache(string key)
        {
            using (var db = GetDb())
                return db.GetCache(key);
        }
        public static T GetCache<T>(string key, bool updateExpirationDate = false)
        {
            using (var db = GetDb())
            {
                var value = db.GetCache(key);
                if (string.IsNullOrEmpty(value))
                    return default(T);
                return JsonHelper.Parse<T>(value);
            }
        }
        #endregion
    }
}
